'use strict'

class image {

  constructor () {
    //路由参数
    this.param = '/:name'

    this.allowTypes = [
      'image/jpeg', 'image/png', 'image/gif', 'image/webp', 'image/x-icon'
    ]
  }

  /**
   * 获取资源具体内容
   * @param {context} c
   * @returns 
   */
  async get (c) {
    try {
      await c.helper.pipe(`${c.service.storagePath}/images/${c.param.name}`, c.reply)
    } catch (err) {
      return c.status(404)
    }
  }

  checkImageType(img) {
    if (!img['content-type']) img['content-type'] = 'image/webp'

    if (this.allowTypes.indexOf(img['content-type']) < 0) return false

    return true
  }

  /**
   * 创建资源
   * @param {context} c
   * @returns 
   */
  async post (c) {
    let imgfile = c.getFile('image')
    if (!imgfile) {
      return c.status(400).send('image not found')
    }

    if (!this.checkImageType(imgfile)) {
      return c.status(400).send('未知图片类型。')
    }

    let imagePath = c.service.storageDir + '/images'
    let imageName = ''

    //使用事务执行上传图片并记录到media表的操作。
    let r = await c.service.media.transaction(async (db, ret) => {
      imageName = c.helper.makeName(imgfile.filename)
      let tm = Date.now()

      let img = await db.returning('id')
                        .insert({
                          name: imageName,
                          mime_type: imgfile['content-type'],
                          create_time: tm,
                          update_time: tm
                        })

      await imgfile.toFile(imagePath, imageName)

      ret.result = {
        id: img.id,
        name: imageName
      }
      
    })

    if (!r.ok) {
      return c.status(400).send(r.errmsg)
    }

    c.send(r.result)
  }

  /**
   * 获取列表
   * @param {context} c
   * @returns 
   */
  async list (c) {

  }

  /**
   * 删除资源
   * @param {context} c
   * @returns 
   */
  async delete (c) {
    let ret = await c.service.media.remove(c.param.name)
    if (!ret.ok) {
      return c.status(400).send(ret.errmsg)
    }

    return c.send(ret.result || 'ok')
  }
  
}

module.exports = image
